import { ResultPage, Card } from 'antd-mobile'
import {  SearchBar } from 'antd-mobile'
import { NoticeBar} from 'antd-mobile'
import { CapsuleTabs } from 'antd-mobile'
import { DownOutline } from 'antd-mobile-icons'
import axios from '../../api/http'
import { useEffect, useState, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'

import Yue from '../../assets/预约挂号.png'
import ji from '../../assets/极速问诊.png'
import fu from '../../assets/复诊开房费.png'
import liveIcon from '../../assets/义诊直播.png'
import scienceIcon from '../../assets/健康科普.png'
import shopIcon from '../../assets/商城买药.png'
import adviceIcon from '../../assets/用药建议.png'
import myDoctorIcon from '../../assets/我的医生.png'

function Index() {
  const nav=useNavigate()
  type Doctor = { doctorid?: string|number; id?: string|number; doctorname?: string; name?: string; doctorimage?: string; avatar?: string; doctorstate?: string; doctortitle?: string; socoadmin?: string; doctorministre?: string; doctorcity?: string; doctorprice?: number; price?: number; rating?: number; flags?: number; views?: number }
  type Drug = { id?: string|number; name?: string; image?: string; price?: number; manufacturer?: string; specification?: string; category?: string; isOTC?: boolean }
 
  const [list,setlist]=useState<Doctor[]>([ ])
  const [drugList, setDrugList] = useState<Drug[]>([])
  const [activeTab,setActiveTab]=useState<string>('妇产科')
  const [activeDrugTab, setActiveDrugTab] = useState<string>('皮肤用药')
  const departments = ['妇产科','儿科','皮肤科','心血管内科','呼吸内科','消化内科','中医科','口腔科']
  const drugCategories = ['皮肤用药','男科用药','妇科用药','儿科用药']

  const fetchDoctors = useCallback(async (admin?: string) => {
    try {
      const res = await axios.get('/doctor/list', { params: { pageCode: 1, pageSize: 10, admin } }) as unknown as { data?: Doctor[]; list?: Doctor[] } | Doctor[]
      const data = (Array.isArray(res) ? res : (res?.data || res?.list || [])) as Doctor[]
      setlist(Array.isArray(data) ? data : [])
    } catch {
      setlist([ ])
      
    }
  }, [])

  // 模拟不同分类的药品数据
  const mockDrugData = {
    '皮肤用药': [
      {
        id: '1',
        name: '皮炎平软膏',
        image: 'https://via.placeholder.com/120x120/FF6B6B/FFFFFF?text=皮炎平',
        price: 12.8,
        manufacturer: '三九医药',
        specification: '15g',
        isOTC: true,
        category: '皮肤用药'
      },
      {
        id: '2',
        name: '999皮炎平',
        image: 'https://via.placeholder.com/120x120/4ECDC4/FFFFFF?text=999',
        price: 18.5,
        manufacturer: '华润三九',
        specification: '20g',
        isOTC: true,
        category: '皮肤用药'
      },
      {
        id: '3',
        name: '红霉素软膏',
        image: 'https://via.placeholder.com/120x120/45B7D1/FFFFFF?text=红霉素',
        price: 8.9,
        manufacturer: '白云山',
        specification: '10g',
        isOTC: true,
        category: '皮肤用药'
      },
      {
        id: '4',
        name: '炉甘石洗剂',
        image: 'https://via.placeholder.com/120x120/96CEB4/FFFFFF?text=炉甘石',
        price: 15.2,
        manufacturer: '同仁堂',
        specification: '100ml',
        isOTC: true,
        category: '皮肤用药'
      }
    ],
    '男科用药': [
      {
        id: '5',
        name: '前列康片',
        image: 'https://via.placeholder.com/120x120/FFEAA7/FFFFFF?text=前列康',
        price: 45.6,
        manufacturer: '康恩贝',
        specification: '60片',
        isOTC: false,
        category: '男科用药'
      },
      {
        id: '6',
        name: '六味地黄丸',
        image: 'https://via.placeholder.com/120x120/DDA0DD/FFFFFF?text=六味',
        price: 32.8,
        manufacturer: '同仁堂',
        specification: '200丸',
        isOTC: true,
        category: '男科用药'
      },
      {
        id: '7',
        name: '金匮肾气丸',
        image: 'https://via.placeholder.com/120x120/98D8C8/FFFFFF?text=金匮',
        price: 28.9,
        manufacturer: '太极集团',
        specification: '360丸',
        isOTC: true,
        category: '男科用药'
      },
      {
        id: '8',
        name: '复方玄驹胶囊',
        image: 'https://via.placeholder.com/120x120/F7DC6F/FFFFFF?text=玄驹',
        price: 68.5,
        manufacturer: '施强药业',
        specification: '36粒',
        isOTC: false,
        category: '男科用药'
      }
    ],
    '妇科用药': [
      {
        id: '9',
        name: '乌鸡白凤丸',
        image: 'https://via.placeholder.com/120x120/BB8FCE/FFFFFF?text=乌鸡',
        price: 25.8,
        manufacturer: '同仁堂',
        specification: '9g*10袋',
        isOTC: true,
        category: '妇科用药'
      },
      {
        id: '10',
        name: '益母草颗粒',
        image: 'https://via.placeholder.com/120x120/85C1E9/FFFFFF?text=益母草',
        price: 18.6,
        manufacturer: '太极集团',
        specification: '15g*10袋',
        isOTC: true,
        category: '妇科用药'
      },
      {
        id: '11',
        name: '逍遥丸',
        image: 'https://via.placeholder.com/120x120/F8C471/FFFFFF?text=逍遥',
        price: 22.9,
        manufacturer: '仲景宛西',
        specification: '200丸',
        isOTC: true,
        category: '妇科用药'
      },
      {
        id: '12',
        name: '妇科千金片',
        image: 'https://via.placeholder.com/120x120/82E0AA/FFFFFF?text=千金',
        price: 35.2,
        manufacturer: '千金药业',
        specification: '108片',
        isOTC: true,
        category: '妇科用药'
      }
    ],
    '儿科用药': [
      {
        id: '13',
        name: '小儿氨酚黄那敏颗粒',
        image: 'https://via.placeholder.com/120x120/FADBD8/FFFFFF?text=氨酚',
        price: 12.5,
        manufacturer: '葵花药业',
        specification: '6g*10袋',
        isOTC: true,
        category: '儿科用药'
      },
      {
        id: '14',
        name: '小儿柴桂退热颗粒',
        image: 'https://via.placeholder.com/120x120/D5DBDB/FFFFFF?text=柴桂',
        price: 28.8,
        manufacturer: '康芝药业',
        specification: '5g*12袋',
        isOTC: true,
        category: '儿科用药'
      },
      {
        id: '15',
        name: '小儿消积止咳口服液',
        image: 'https://via.placeholder.com/120x120/FCF3CF/FFFFFF?text=消积',
        price: 32.6,
        manufacturer: '鲁南制药',
        specification: '10ml*6支',
        isOTC: true,
        category: '儿科用药'
      },
      {
        id: '16',
        name: '小儿肺热咳喘颗粒',
        image: 'https://via.placeholder.com/120x120/D7DBDD/FFFFFF?text=肺热',
        price: 24.9,
        manufacturer: '葵花药业',
        specification: '3g*12袋',
        isOTC: true,
        category: '儿科用药'
      }
    ]
  };

  const fetchDrugs = useCallback(async (category?: string) => {
    try {
      // 使用模拟数据，确保每个分类都有不同的数据
      const mockData = mockDrugData[category as keyof typeof mockDrugData] || mockDrugData['皮肤用药'];
      setDrugList(mockData);
      
    } catch {
      // 如果出错，使用模拟数据
      const mockData = mockDrugData[category as keyof typeof mockDrugData] || mockDrugData['皮肤用药'];
      setDrugList(mockData);
    }
  }, [])

  useEffect(()=>{ fetchDoctors(activeTab) },[activeTab, fetchDoctors])
  useEffect(()=>{ fetchDrugs(activeDrugTab) },[activeDrugTab, fetchDrugs])
    
  
  return (
    <div style={{width:'100vw',height:'100vh'}}>
      {/* 自定义顶部导航栏 */}
      <div style={{
        background: '#1677ff',
        padding: '16px',
        color: '#fff',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between'
      }}>
        {/* 左侧标题 */}
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          gap: '2px'
        }}>
          <div style={{
            fontSize: '18px',
            fontWeight: 'bold',
            lineHeight: '1.2'
          }}>
            妙手医生 <span style={{
            fontSize: '14px',
            opacity: 0.9,
            lineHeight: '1.2'
          }}>
            妙手互联网医院
          </span>
          </div>
         
        </div>

        {/* 右侧城市选择器 */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: '4px',
          cursor: 'pointer'
        }}>
          <span style={{
            fontSize: '14px',
            fontWeight: ''
          }} onClick={()=>nav('/loc')}>
            北京
          </span>
          <DownOutline style={{
            fontSize: '12px',
            color: '#fff'
          }} />
        </div>
      </div>

     <ResultPage
      status=''
      title=''
      description=''
      style={{border:'none',marginTop:'-15px'}} >
          <SearchBar placeholder='搜索医生、医院、药品、疾病症状'
          onFocus={()=>nav('/search')} style={{ overflow: 'auto',marginTop:'-50px'}}/>
              <NoticeBar style={{borderRadius:'10px'}}
              content='公告:1、自治区卫生热线250-456123789 妙手互联网热线1223-456123 2、为了更好的服务您,即日起您点击预约挂号，请务必填写真实姓名和联系方式。'
               color='alert' />
            <ResultPage.Card style={{ padding: 12 }}>
      

              {/* 三大功能入口 */}
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center', padding:'10px 6px'}}>
                <div onClick={()=>nav('/yu')} style={{width:'33%',textAlign:'center',cursor:'pointer'}}>
                  <img src={Yue} alt="预约挂号" style={{width:'56px',height:'56px'}}/>
                  <div style={{marginTop:'6px',fontWeight:700}}>预约挂号</div>
                  <div style={{marginTop:'2px',fontSize:'12px',color:'#bfbfbf'}}>30W+专家入驻</div>
                </div>
                <div onClick={()=>nav('/ji')} style={{width:'33%',textAlign:'center',cursor:'pointer'}}>
                  <img src={ji} alt="极速问诊" style={{width:'56px',height:'56px'}}/>
                  <div style={{marginTop:'6px',fontWeight:700}}>极速问诊</div>
                  <div style={{marginTop:'2px',fontSize:'12px',color:'#bfbfbf'}}>平均3分钟接诊</div>
                </div>
                <div onClick={()=>nav('/fu')} style={{width:'33%',textAlign:'center',cursor:'pointer'}}>
                  <img src={fu} alt="复诊开方" style={{width:'56px',height:'56px'}}/>
                  <div style={{marginTop:'6px',fontWeight:700}}>复诊开方</div>
                  <div style={{marginTop:'2px',fontSize:'12px',color:'#bfbfbf'}}>慢病续方送到家</div>
                </div>
              </div>

              {/* 次级入口 */}
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center', padding:'6px 12px 2px'}}>
                <div style={{textAlign:'center'}}>
                  <img src={myDoctorIcon} alt="问专家" style={{width:28,height:28}}/>
                  <div style={{marginTop:4,fontSize:12}}>问专家</div>
                </div>
                <div style={{textAlign:'center'}}>
                  <img src={adviceIcon} alt="开药门诊" style={{width:28,height:28}}/>
                  <div style={{marginTop:4,fontSize:12}}>开药门诊</div>
                </div>
                <div style={{textAlign:'center'}}>
                  <img src={liveIcon} alt="义诊直播" style={{width:28,height:28}}/>
                  <div style={{marginTop:4,fontSize:12}}>义诊直播</div>
                </div>
                <div style={{textAlign:'center'}}>
                  <img src={scienceIcon} alt="健康科普" style={{width:28,height:28}}/>
                  <div style={{marginTop:4,fontSize:12}}>健康科普</div>
                </div>
                <div style={{textAlign:'center'}}>
                  <img src={shopIcon} alt="商城买药" style={{width:28,height:28}}/>
                  <div style={{marginTop:4,fontSize:12}}>商城买药</div>
                </div>
              </div>
            </ResultPage.Card>

      <Card style={{ marginTop: 12 }}>
<div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
  <h2 style={{margin:0}}>我要问专家</h2>
  <span
    onClick={()=>nav('/more')}
    style={{
      display:'inline-flex',alignItems:'center',gap:'6px',
      padding:'4px 10px',
      fontSize:'12px',color:'#9e9e9e',
      background:'#f5f5f5',
      borderRadius:'999px',
      cursor:'pointer'
    }}>
      更多 <span style={{fontSize:'14px'}}>›</span>
  </span>
</div>
        <CapsuleTabs activeKey={activeTab} onChange={setActiveTab}>
          {departments.map(d => (
            <CapsuleTabs.Tab title={d} key={d} />
          ))}
        </CapsuleTabs>
    <div>
    {list && list.length>0 ? (     
     list.slice(0, 2).map((item:Doctor,index:number)=> {
        const name = item?.doctorname || item?.name || '专家';
        const avatar = item?.doctorimage || item?.avatar || 'https://via.placeholder.com/56';
        const title = item?.doctorstate || item?.doctortitle || '';
        const department = item?.socoadmin || item?.doctorministre || '';
        const city = item?.doctorcity || '';
        const price = item?.doctorprice || item?.price;
        const docId = item?.doctorid || item?.id || index;
        const rating = item?.rating ?? 100;
        const flags = item?.flags ?? 3;
        const views = item?.views ?? 12000;
        const pillTags = [department, city].filter(Boolean).slice(0,2);
        return (
          <div
            key={item.doctorid || item.id || index}
            style={{
              display:'flex',
              alignItems:'center',
              gap:'12px',
              padding:'12px 0',
              borderBottom:'1px solid #f2f2f2'
            }}
          >
            <img
              src={avatar}
              alt="avatar"
              style={{width:'56px',height:'56px',borderRadius:'50%'}}
            />
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:'flex',alignItems:'center',gap:'8px'}}>
                <div style={{fontSize:'15px',fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{name}</div>
                {title ? <span style={{fontSize:'12px',color:'#666'}}>{title}</span> : null}
              </div>
              {pillTags.length ? (
                <div style={{marginTop:'6px',display:'flex',gap:'6px',flexWrap:'wrap'}}>
                  {pillTags.map((t:string,i:number)=> (
                    <span key={i} style={{fontSize:'12px',color:'#1677ff',background:'#eaf3ff',padding:'2px 6px',borderRadius:'10px'}}>{t}</span>
                  ))}
                </div>
              ) : null}
              <div style={{marginTop:'8px',fontSize:'12px',color:'#999'}}>
                好评率 {rating}%  锦旗 {flags}  浏览人次 {typeof views === 'number' ? views.toLocaleString() : views}
              </div>
            </div>
            <div style={{textAlign:'right',minWidth:'80px'}}>
              <div style={{color:'#ff6b00',fontWeight:600}}>{price ? `¥${price}` : ''}</div>
              <button onClick={()=>nav(`/detail?id=${encodeURIComponent(String(docId))}`)} style={{marginTop:'6px',background:'#1677ff',color:'#fff',border:'none',borderRadius:'14px',padding:'6px 12px'}}>问医生</button>
            </div>
          </div>
        )
      })
    ) : (
      <div style={{textAlign:'center',color:'#999',padding:'20px 0'}}>暂无数据</div>    
    )}
    
    </div>

     <div style={{textAlign:'center'}}><a href="/more">查看此科室更多医生</a></div>
      </Card>

      {/* 我要买药部分 */}
      <Card style={{ marginTop: 12 }}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
          <h2 style={{margin:0}}>我要买药</h2>
          <span
            onClick={()=>nav('/shop')}
            style={{
              display:'inline-flex',alignItems:'center',gap:'6px',
              padding:'4px 10px',
              fontSize:'12px',color:'#9e9e9e',
              background:'#f5f5f5',
              borderRadius:'999px',
              cursor:'pointer'
            }}>
            更多 <span style={{fontSize:'14px'}}>›</span>
          </span>
        </div>
        
        <CapsuleTabs activeKey={activeDrugTab} onChange={setActiveDrugTab}>
          {drugCategories.map(d => (
            <CapsuleTabs.Tab title={d} key={d} />
          ))}
        </CapsuleTabs>

        <div style={{
          display: 'grid',
          gridTemplateColumns: '1fr 1fr',
          gap: '12px',
          marginTop: '12px'
        }}>
          {drugList && drugList.length > 0 ? (
            drugList.map((item: Drug, index: number) => {
              const name = item?.name || '药品名称';
              const image = item?.image || 'https://via.placeholder.com/120x120';
              const price = item?.price || 0;
              const manufacturer = item?.manufacturer || '';
              const specification = item?.specification || '';
              const isOTC = item?.isOTC ?? true;
              const drugId = item?.id || index;
              return (
                <div
                  key={item.id || index}
                  style={{
                    background: '#fff',
                    borderRadius: '8px',
                    padding: '12px',
                    border: '1px solid #f0f0f0',
                    cursor: 'pointer'
                  }}
                  onClick={() => nav(`/shop/detail?id=${encodeURIComponent(String(drugId))}`)}
                >
                  <div style={{textAlign: 'center', marginBottom: '8px'}}>
                    <img
                      src={image}
                      alt={name}
                      style={{
                        width: '80px',
                        height: '80px',
                        objectFit: 'contain',
                        borderRadius: '4px'
                      }}
                    />
                  </div>
                  
                  <div style={{marginBottom: '6px'}}>
                    <div style={{
                      fontSize: '13px',
                      fontWeight: 600,
                      color: '#333',
                      lineHeight: '1.3',
                      marginBottom: '4px',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical',
                      overflow: 'hidden'
                    }}>
                      {name}
                    </div>
                    
                    {isOTC && (
                      <span style={{
                        fontSize: '10px',
                        color: '#1677ff',
                        background: '#eaf3ff',
                        padding: '2px 6px',
                        borderRadius: '4px',
                        marginRight: '4px'
                      }}>
                        OTC
                      </span>
                    )}
                    
                    {specification && (
                      <span style={{
                        fontSize: '10px',
                        color: '#666',
                        background: '#f5f5f5',
                        padding: '2px 6px',
                        borderRadius: '4px'
                      }}>
                        {specification}
                      </span>
                    )}
                  </div>
                  
                  <div style={{
                    fontSize: '11px',
                    color: '#999',
                    marginBottom: '6px',
                    display: '-webkit-box',
                    WebkitLineClamp: 1,
                    WebkitBoxOrient: 'vertical',
                    overflow: 'hidden'
                  }}>
                    {manufacturer}
                  </div>
                  
                  <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center'
                  }}>
                    <span style={{
                      color: '#ff6b00',
                      fontSize: '16px',
                      fontWeight: 600
                    }}>
                      ¥{price}
                    </span>
                    <button style={{
                      background: '#1677ff',
                      color: '#fff',
                      border: 'none',
                      borderRadius: '12px',
                      padding: '4px 8px',
                      fontSize: '11px',
                      cursor: 'pointer'
                    }}>
                      立即购买
                    </button>
                  </div>
                </div>
              )
            })
          ) : (
            <div style={{
              gridColumn: '1 / -1',
              textAlign: 'center',
              color: '#999',
              padding: '20px 0'
            }}>
              暂无药品数据
            </div>
          )}
        </div>

        <div style={{textAlign:'center', marginTop: '12px'}}>
          <a href="/shop" style={{color: '#1677ff', fontSize: '14px'}}>
            查看此分类下更多药品
          </a>

        </div>
      </Card>
       
    </ResultPage>
     
    
    </div>
  )
}

export default Index